<template>
	<div class="vmall-cart">
		<HeadNav title="购物车" bgColor="#fff" @getHeadHeight="getHeadHeight" :backIcon="true" path='/pages/index/index'>
			<template #left>
				<view class="shopcartheader" :style="{paddingRight:BoundingWidth+'px'}">
					<text>购物车</text>
					<text class="f-26" @click="onRightEdit">{{ showBottom ? '退出管理' : '管理' }}</text>
				</view>
			</template>
		</HeadNav>
		<div class="page-content">
			<div v-if="cartList.length > 0">
				<Cart ref="cartRef" :cartList="cartList" @delete="onDelete" @select="onSelect" @minus="onMinus"
					@add="onAdd" @select1="onSelect1" />
				<!-- 底部-删除 -->
				<div v-if="showBottom">
					<div class="del-bottom">
						<div class="cart-bottom-cell" @click="onCancel">取消</div>

						<div class="cart-bottom-cell del-color" @click="onDeleteAll">删除({{ deleteCount }})</div>
					</div>
				</div>
				<!-- 底部-结算 -->
				<div v-else>
					<div class="cart-bottom">
						<div class="cart-bottom-icon">
							<image :src="IMG_URL2 + 'login/checkbox1.svg'" v-if="CheckAll" @click="onSelectAll" />
							<image :src="IMG_URL2 + 'login/checkbox.svg'" v-else @click="onSelectAll" />
						</div>
						<div class="checkAll">全选</div>
						<div class="cart-sum">
							<text class="sum_text">共</text>
							<text class="sum_text">{{ goodsCount }}件，</text>
							<text class="sum_text">合计：</text>
							<text class="sum_color">￥{{ totalPrice }}</text>
						</div>
						<div class="cart-pay">
							<text class="cart_pay" @click="onPayOrder">去结算</text>
						</div>
					</div>
				</div>
			</div>
			<!-- 如果无数据，则显示数据 -->
			<div class="empty-container py-40" v-else>
				<Empty :emptyInfo="emptyInfo" />
			</div>
		</div>
		<SalesButton />
	</div>
</template>
<script setup>
import { IMG_URL2 } from "@/config";
import { shopApi } from "@/api";
import HeadNav from "@/components/headnav.vue";
import Cart from "@/components/cart.vue";
import Empty from "@/components/empty.vue";
import SalesButton from "@/components/salesbutton.vue";

let pageSize = ref(10)
let currentPage = ref(1)
let totalCount = ref(0)
let loadStatus = ref('正在加载中')
const cartList = ref([]);
const totalPrice = ref(0);
const CheckAll = ref(false);
const goodsCount = ref(0);
const deleteCount = ref(0);
const showBottom = ref(false);

let BoundingWidth =ref(30)
const EmptyImage = ref(IMG_URL2 + "empty/cart.png");
const emptyInfo = ref({
	image: EmptyImage,
	width: 300,
	height: 300,
	tip: "小车大容量，喜欢的都加进来吧"
});
// 商品瀑布流列表
// const loadStatus = ref("loadmore");
const flowList = ref([]);
const goodsList = ref([]);
const waterfallRef = ref();
// 返回顶部
const backTop = ref(0);
const cartRef = ref();

onLoad(() => {
	let res = wx.getMenuButtonBoundingClientRect();
	BoundingWidth.value = res.width;
});
onShow(() => {
    getData();
})

const getHeadHeight=(data)=>{

}

// 购物车
// 全选
const onSelectAll = (e) => {
	// for (let i = 0; i < cartList.value.length; i++) {
	// 	cartList.value[i].selected = !CheckAll.value;
	// 	for (let n = 0; n < cartList.value[i].skuList.length; n++) {
	// 		cartList.value[i].skuList[n].selected = !CheckAll.value;
	// 	}
	// }
	// CheckAll.value = !CheckAll.value;

	const newState = !CheckAll.value;
	// Update all parent and child items
	cartList.value.forEach(item => {
			item.selected = newState;
		item.skuList.forEach(sku => {
			sku.selected = newState;
		});
	});
	
	CheckAll.value = newState;

	getSumTotal();
	getGoodsCount();
	deleteGoodsCount();
};
// 反选
const onSelect = (index) => {
	// cartList.value[index].selected = !cartList.value[index].selected;
	// for (let n = 0; n < cartList.value[index].skuList.length; n++) {
	// 	cartList.value[index].skuList[n].selected = !cartList.value[index].skuList[n].selected
	// }
	// CheckAll.value = !cartList.value.some((item) => item.selected == false);

	const item = cartList.value[index];
    item.selected = !item.selected;
    
    item.skuList.forEach(sku => {
        sku.selected = item.selected;
    });

    CheckAll.value = cartList.value.every(item => 
        item.selected && item.skuList.every(sku => sku.selected)
    );
	getSumTotal();
	getGoodsCount();
	deleteGoodsCount();
};

// 单个反选
const onSelect1 = (index,nindex) => {
	// cartList.value[index].skuList[nindex].selected = !cartList.value[index].skuList[nindex].selected;
	// CheckAll.value = !cartList.value.some((item) => item.selected == false);

	const item = cartList.value[index];
    const sku = item.skuList[nindex];
    sku.selected = !sku.selected;
    
    item.selected = item.skuList.every(sku => sku.selected);

    CheckAll.value = cartList.value.every(item => 
        item.selected && item.skuList.every(sku => sku.selected)
    );
	getSumTotal();
	getGoodsCount();
	deleteGoodsCount();
};
// 加
const onAdd = (index,nindex) => {
	cartList.value[index].skuList[nindex].quantity++;
	getSumTotal();
	getGoodsCount();
};
// 减
const onMinus = (index,nindex) => {
	if (cartList.value[index].skuList[nindex].quantity == 1) {
		uni.showToast({
			title: '不能再减了哦',
			icon: "none",
			duration: 1000
		});
		return;
	}
	cartList.value[index].skuList[nindex].quantity--;
	getSumTotal();
	getGoodsCount();

};
// 单个删除选中的商品
const onDelete = (index) => {
	// 处理u-swipe-action-item不复位的问题(要放在删除操作的上方)
	console.log(cartList.value[index],'cartList.value[index]');
	cartRef.value.resetSwipeAction();
	cartList.value.splice(index, 1);
	getSumTotal();
	getGoodsCount();
	deleteGoodsCount();
};
// 批量删除选中的商品
const onDeleteAll = (e) => {
	let ids = [];
	for (let i = 0; i < cartList.value.length; i++) {
		for (let n = 0; n < cartList.value[i].skuList.length; n++) {
			if (cartList.value[i].skuList[n].selected) {
				ids.push(cartList.value[i].skuList[n].purchaseCartId);
				// cartList.value[i].skuList.splice(n, 1);
				// n--; // Adjust index after splicing
			}
		}
		if (cartList.value[i].skuList.length === 0) {
			// cartList.value.splice(i, 1);
			// i--; // Adjust index after splicing
		}
	}
	console.log(ids, 'ids');
	if (ids.length === 0) {
		uni.showToast({
			title: '请勾选删除的商品',
			icon: "none",
			duration: 1000
		});
		return;
	}
	shopApi.PURCHASECARTBATCHDELETE({ids: ids}).then((res) => {
		if (res.code == 200) {
			totalPrice.value = 0;
			goodsCount.value = 0;
			deleteCount.value = 0;
			console.log(ids, 'ids');
			uni.showToast({
				title: '删除成功',
				icon: "none",
				duration: 1000
			});
			getData();
			CheckAll.value = false;
		} else {
			uni.showToast({
				title: res.errMsg,
				icon: "none",
				duration: 1000
			});
		}
	}).catch((err) => {
		
	});
};
// 删除数量方法
const deleteGoodsCount = () => {
	let count = 0;
	for (let i = 0; i < cartList.value.length; i++) {
		// if (cartList.value[i].selected) {
		// 	count = count + 1;
		// }
		for (let n = 0; n < cartList.value[i].skuList.length; n++) {
			if (cartList.value[i].skuList[n].selected) {
				// sum += cartList.value[i].skuList[n].quantity * cartList.value[i].skuList[n].unitPrice;
				count = count + 1;
			}
		}
	}
	deleteCount.value = count;
};
// 合计
const getSumTotal = () => {
	let sum = 0;
	for (let i = 0; i < cartList.value.length; i++) {
		for (let n = 0; n < cartList.value[i].skuList.length; n++) {
			if (cartList.value[i].skuList[n].selected) {
				// sum += cartList.value[i].skuList[n].quantity * cartList.value[i].skuList[n].unitPrice;
				sum += cartList.value[i].skuList[n].quantity * cartList.value[i].unitPrice;
			}
		}
	}
	totalPrice.value = sum;
};
// 商品总数量
const getGoodsCount = () => {
	let count = 0;
	for (let i = 0; i < cartList.value.length; i++) {
		for (let n = 0; n < cartList.value[i].skuList.length; n++) {
			if (cartList.value[i].skuList[n].selected) {
				// sum += cartList.value[i].skuList[n].quantity * cartList.value[i].skuList[n].unitPrice;
				count = count + Number(cartList.value[i].skuList[n].quantity)
			}
		}
		// if (cartList.value[i].selected) {
		// 	count = count + 1;
		// }
	}
	goodsCount.value = count;
};
// 编辑
const onRightEdit = () => {
	showBottom.value = !showBottom.value;
};
// 取消删除功能
const onCancel = () => {
	showBottom.value = false;
};
// 结算
const onPayOrder = () => {
	if (goodsCount.value > 0) {
		const newresult = [];

		const grouped = {};

		cartList.value.forEach((parentItem) => {
			const parentKey = JSON.stringify({
				purchaseCartId: parentItem.purchaseCartId,
				productId: parentItem.productId,
				name: parentItem.name,
				productImg: parentItem.productImg,
				unitPrice: parentItem.unitPrice
			});

			if (!grouped[parentKey]) {
				grouped[parentKey] = {
				...parentItem,
					skuList: []
				};
			}

			parentItem.skuList.forEach((skuItem) => {
				if (skuItem.selected) {
					grouped[parentKey].skuList.push(skuItem);
				}
			});
		});

		for (const key in grouped) {
			newresult.push(grouped[key]);
		}
		let newresult1=newresult.filter(item => item.skuList.length > 0)
		console.log(newresult1,'newresult')
		uni.navigateTo({ 
			url: "/pages/order/confirm?spec=" + JSON.stringify(newresult1) + "&type=goods"
		 });
	} else {
		uni.showToast({
			title: "您还没有选择商品哦",
			icon: "none",
			mask: true
		});
	}
};

// 监听页面滚动(返回顶部)
onPageScroll((e) => {
	backTop.value = e.scrollTop;
});

// 触底加载
onReachBottom(() => {
	console.log("触底加载");
	if (flowList.value.length > 32) {
		loadStatus.value = "nomore";
		return;
	}
	loadStatus.value = "loading";
	getData();
});
// 下拉刷新
onPullDownRefresh(() => {
	console.log("下拉刷新");
	currentPage.value = 1;
	showBottom.value = false;
	CheckAll.value = false;
	// 瀑布流数据清空
	if (waterfallRef.value) {
		waterfallRef.value.onClear();
	}
	// 正常情况下接口返回应该很会很快。故意延迟调用，让用户有在刷新的体验感
	loadStatus.value = "loading";
	flowList.value = [];
	setTimeout(() => {
		getData();
		uni.stopPullDownRefresh();
	}, 300);
});
// 获取购物车数
const getpurchaseCartcount = () => {
	shopApi.PURCHASECARTCOUNT().then((res) => {
		if (res.code == 200) {

		}else{
            uni.showToast({
                title: res.errMsg,
                icon: "success",
            });
        }

	})

};
const getData = () => {
	let params = {
		currentPage: currentPage.value,
		pageSize: pageSize.value
	}
	shopApi.PURCHASECARTLIST(params).then((res) => {
		if (res.code == 200) {
			cartList.value = res.result.data;
			// getGoodsCount();
			// getTotalPrice();
			// getpurchaseCartcount();
		}else{
            uni.showToast({
                title: res.errMsg,
                icon: "success",
            });
        }

	})

};
</script>

<style>
page {
	background-color: #ededed;
}
</style>
<style lang="scss" scoped>
.shopcartheader{
	width: 100%;
	box-sizing: border-box;
	display: flex;
	align-items: center;
	justify-content: space-between;
}
.vmall-cart {
	.header {

		/* #ifdef APP-PLUS */
		:deep .u-navbar--fixed {
			top: var(--status-bar-height);
		}
		/* #endif */
	}

	.page-content {
		.cart-main {
			display: flex;
			margin-right: 20rpx;
		}

		.cart-active {
			float: left;
			width: 100%;
			background: #ffffff;
			border-bottom: 2rpx solid #f2f2f2;
		}

		.cart-image {
			width: 200rpx;
			height: 200rpx;
			float: left;
			margin: 20rpx 10rpx;
		}

		.cart-box {
			display: flex;
			background: white;
			border-radius: 8rpx;
		}

		.cart-boxtwo {
			display: flex;
			flex-direction: column;
		}

		.left_box {
			margin-left: 8rpx;
			margin-top: 20rpx;
			line-height: 60rpx;
		}

		.cart-title {
			font-size: 28rpx;
			line-height: 34rpx;
			display: -webkit-box;
			-webkit-box-orient: vertical;
			overflow: hidden;
			-webkit-line-clamp: 2;
		}

		.cart-count {
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.cart-unit {
			font-size: 24rpx;
			color: rgba(214, 142, 68, 1);
		}

		.cart-money {
			display: flex;
			align-items: center;
		}

		.cart-price {
			display: flex;
			color: rgba(214, 142, 68, 1);
			font-size: 30rpx;
			height: 36rpx;
			line-height: 36rpx;
		}

		.cart-specif {
			padding: 4rpx 12rpx;
			box-sizing: border-box;
			background: rgba(214, 142, 68, 1);
			color: #ffffff;
			font-size: 24rpx;
			height: 36rpx;
			line-height: 36rpx;
			margin-bottom: 10rpx;
			border-radius: 50rpx;
		}

		.right {
			float: right;
			width: 5%;
		}

		.right image {
			width: 50rpx;
			height: 50rpx;
			float: right;
			margin-right: 30rpx;
		}

		.input {
			display: block;
			width: 65rpx;
			height: 65rpx;
			line-height: 65rpx;
			text-align: center;
			float: left;
		}

		.cart-add {
			border-left: none;
			border: 2rpx solid #ededed;
			border-radius: 0rpx 40rpx 40rpx 0rpx;
			font-size: 36rpx;
		}

		.cart-reduce {
			border-right: none;
			border: 2rpx solid #ededed;
			border-radius: 40rpx 0rpx 0rpx 40rpx;
			font-size: 36rpx;
		}

		.cart-text {
			width: 90rpx;
			border-top: 2rpx solid #ededed;
			border-bottom: 2rpx solid #ededed;
			font-size: 30rpx;
		}

		.cart-bottom {
			display: flex;
			position: fixed;
			align-items: center;
			width: 100%;
			height: 88rpx;
			bottom: var(--window-bottom);
			background: #ffffff;
			padding: 0rpx 20rpx;
			box-sizing: border-box;
			border-top: 2rpx solid #f2f2f2;
			z-index: 9;
		}

		.cart-bottom-icon {
			// margin-top: 22rpx;

			image {
				width: 40rpx !important;
				height: 40rpx !important;
			}
		}

		.yuan {
			display: block;
			width: 50rpx;
			height: 50rpx;
			border-radius: 50%;
			border: 2rpx solid red;
		}

		.SpCart {
			display: block;
			width: 300rpx;
			height: 300rpx;
		}

		.Sptext {
			font-size: 30rpx;
		}

		.cart-icon {
			margin: 26rpx 20rpx;
			float: left;
		}

		.cart-sum {
			width: 300rpx;
			height: 100%;
			line-height: 87rpx;
			float: left;
			text-align: center;
			margin-left: 20rpx;
			font-size: 28rpx;
		}

		.cart-pay {
			position: absolute;
			width: 230rpx;
			height: 100%;
			background: rgba(214, 142, 68, 1);
			right: 0;
		}

		.cart_pay {
			display: block;
			line-height: 87rpx;
			text-align: center;
			font-size: 30rpx;
			color: white;
		}

		.sum_color {
			color: rgba(213, 73, 65, 1);
			font-family: PingFang SC;
			font-size: 16px;
			font-weight: 600;
			line-height: 24px;
			text-align: left;
			text-underline-position: from-font;
			text-decoration-skip-ink: none;

		}

		.sum_text {
			font-family: PingFang SC;
			font-size: 12px;
			font-weight: 400;
			line-height: 20px;
			text-align: left;
			text-underline-position: from-font;
			text-decoration-skip-ink: none;
			color: rgba(0, 0, 0, 0.6);
		}

		.checkAll {
			margin-left: 20rpx;
			line-height: 87rpx;
			font-size: 24rpx;
			color: rgba(0, 0, 0, 0.9);
		}

		.cart-cell {
			display: flex;
			padding: 20rpx 20rpx 0rpx 20rpx;
			box-sizing: border-box;
		}

		.nodata_text {
			background: #ffffff;
			color: black;
			font-size: 28rpx;
			text-align: center;
		}

		.nodata_text {
			image {
				margin-top: 100rpx;
				width: 44%;
				height: 300rpx;
			}
		}

		.icon-main {
			margin: 94rpx 20rpx;
			background: #ffffff;

			image {
				width: 40rpx !important;
				height: 40rpx !important;
			}
		}

		.empty-container {
			background: #ffffff;
		}

		/* 底部 */
		.del-bottom {
			position: fixed;
			width: 100%;
			height: 88rpx;
			bottom: var(--window-bottom);
			background: #ffffff;
			border-top: 2rpx solid #f2f2f2;
			z-index: 999;
		}

		.cart-bottom-edit {
			float: left;
			width: 100%;
			height: 88rpx;
			line-height: 88rpx;
			text-align: center;
			font-size: 28rpx;
			color: rgba(214, 142, 68, 1);
		}

		.cart-bottom-cell {
			float: left;
			width: 49.725%;
			height: 88rpx;
			line-height: 88rpx;
			text-align: center;
			font-size: 28rpx;
			color: #999999;
			border-right: 2rpx solid #f2f2f2;
		}

		.cart-bottom-cell:last-child {
			border-right: 0rpx;
		}

		.del-color {
			color: rgba(214, 142, 68, 1);
		}
	}

	.wrap {
		padding: 0rpx 10rpx 100rpx 10rpx;
		box-sizing: border-box;
	}

	:deep .u-empty {
		background: #ffffff;
		margin-bottom: 40rpx;
		padding-bottom: 40rpx;
	}
}

.cart-right {
	font-size: 26rpx;
}

:deep .u-status-bar {
	display: none !important;
}
</style>